
#include <sys/statfs.h>
#include <string>
#include <iostream>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

/// get executable path
std::string get_cur_executable_path_()
{
    char *p                 = NULL;

    const int len           = 256;
    /// to keep the absolute path of executable's path
    char arr_tmp[len]       = {0};

    int n                   = readlink("/proc/self/exe", arr_tmp, len);
    if (NULL                != (p = strrchr(arr_tmp,'/')))
        *p = '\0';
    else
    {
        printf("wrong process path");
        std::string("");
    }

    return std::string(arr_tmp);
}
 
int main(int argc, char* argv[], char *env[])
{
    /// 读取executable所在绝对路径
    std::string exec_str    = get_cur_executable_path_();
    std::cout << "str=" << exec_str << "\n\n";

    /// 用于获取磁盘剩余空间
	struct statfs diskInfo;
	statfs(exec_str.c_str(), &diskInfo);

	unsigned long long blocksize                = diskInfo.f_bsize;	//每个block里包含的字节数
	unsigned long long totalsize                = blocksize * diskInfo.f_blocks; 	//总的字节数，f_blocks为block的数目

	printf("Total_size = %llu B                 = %llu KB = %llu MB = %llu GB\n", 
		                                            totalsize, totalsize>>10, totalsize>>20, totalsize>>30);
	
	unsigned long long freeDisk                 = diskInfo.f_bfree * blocksize;	//剩余空间的大小
	unsigned long long availableDisk            = diskInfo.f_bavail * blocksize; 	//可用空间大小
	printf("Disk_free = %llu MB                 = %llu GB\nDisk_available = %llu MB = %llu GB\n", 
		                                            freeDisk>>20, freeDisk>>30, availableDisk>>20, availableDisk>>30);
	return 0;

}
